/**
 * 递归生成路由
 * @param {*} router 
 * @param {*} menuList 
 */
export function loopRouter(router, menuList) {
  menuList.forEach((item) => {
    if (item.path && item.component) {
      router.addRoute(item.routerViewName, createRouterItem(item));
    }
    if (item.childList && item.childList.length) {
      loopRouter(router, item.childList);
    }
  });
}

export function createRouterItem(item) {
  return {
    path: item.path,
    name: item.code,
    component: () => import(`@/views${item.component?.substr(0, 1) === '/' ? item.component : `/${item.component}`}`),
    meta: {
      title: item.name,
      icon: item.icon,
      keepAlive: item.keepAlive,
    },
  };
}

/**
 * 递归过滤不显示的菜单
 * @param {*} menuList 
 * @returns 
 */
export function loopMenuFilterIsShow (menuList) {
  const menus = menuList.filter(c => c.isShow === 1);
  menus.forEach(c => {
    if (c.childList && c.childList.length) {
      const list = c.childList.filter(d => d.isShow === 1);
      c.childList = list;
      return loopMenuFilterIsShow(list);
    }
  });
  return menus;
}

export function loopMenuForFlatten (ary) {
  return ary.reduce((pre, cur) => {
    const res = pre.concat(cur);
    if (Array.isArray(cur.childList)) {
      return res.concat(loopMenuForFlatten(cur.childList));
    }
    return res;
  }, []);
}

/**
 * 过滤出来缓存的code
 * @param {*} flattenMenu 
 */
export function getMenuFilterCode (flattenMenu) {
  return flattenMenu.map(c => {
    return c.keepAlive === 1 ? c.code : null
  }).filter(c => c);
}

/**
 * 过滤出来权限集合
 * @param {*} flattenMenu 
 */
export function getMenuFilterPermission (flattenMenu) {
  return flattenMenu.map(c => c.permission).filter(c => c);

}
